package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.dto.PurchaseStorageAddDTO;
import com.intelligent.dto.PurchaseStorageQueryDTO;
import com.intelligent.pojo.PurchaseStorage;
import com.intelligent.pojo.PurchaseSupplier;
import com.intelligent.pojo.TUser;
import com.intelligent.service.PurchaseStorageService;
import com.intelligent.service.PurchaseSupplierService;
import com.intelligent.service.TUserService;
import com.intelligent.mapper.PurchaseStorageMapper;
import com.intelligent.vo.PurchaseStorageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
* @author 86188
* @description 针对表【purchase_storage(采购入库信息表)】的数据库操作Service实现
* @createDate 2025-09-02 10:11:39
*/
@Service
public class PurchaseStorageServiceImpl extends ServiceImpl<PurchaseStorageMapper, PurchaseStorage>
    implements PurchaseStorageService{

    @Autowired
    private PurchaseSupplierService purchaseSupplierService;

    @Autowired
    private TUserService tUserService;

    @Override
    public Page<PurchaseStorageVO> getPurchaseStoragePage(PurchaseStorageQueryDTO queryDTO) {
        // 创建分页对象
        Page<PurchaseStorage> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<PurchaseStorage> queryWrapper = new LambdaQueryWrapper<>();

        // 关键词模糊查询（采购订单号）
        if (StringUtils.hasText(queryDTO.getKeyword())) {
            queryWrapper.like(PurchaseStorage::getStorageOrderNo, queryDTO.getKeyword());
        }

        // 入库状态查询
        if (queryDTO.getStorageStatus() != null) {
            queryWrapper.eq(PurchaseStorage::getStorageStatus, queryDTO.getStorageStatus());
        }

        // 质检状态查询
        if (queryDTO.getQcStatus() != null) {
            queryWrapper.eq(PurchaseStorage::getQcStatus, queryDTO.getQcStatus());
        }

        // 入库时间查询
        if (queryDTO.getStorageTime() != null) {
            queryWrapper.eq(PurchaseStorage::getStorageTime, queryDTO.getStorageTime());
        }

        // 执行查询
        Page<PurchaseStorage> purchaseStoragePage = this.page(page, queryWrapper);

        // 添加调试日志
        System.out.println("=== 后端分页查询结果 ===");
        System.out.println("查询参数 - 页码:" + queryDTO.getPageNum() + ", 每页:" + queryDTO.getPageSize());
        System.out.println("查询结果 - 总数:" + purchaseStoragePage.getTotal() +
                          ", 当前页:" + purchaseStoragePage.getCurrent() +
                          ", 每页大小:" + purchaseStoragePage.getSize() +
                          ", 当前页数据量:" + purchaseStoragePage.getRecords().size());
        System.out.println("=== 后端分页查询结果结束 ===");

        // 转换为VO
        Page<PurchaseStorageVO> voPage = new Page<>();
        // 手动设置分页信息，确保total等字段正确传递
        voPage.setCurrent(purchaseStoragePage.getCurrent());
        voPage.setSize(purchaseStoragePage.getSize());
        voPage.setTotal(purchaseStoragePage.getTotal());
        voPage.setPages(purchaseStoragePage.getPages());

        List<PurchaseStorageVO> voList = purchaseStoragePage.getRecords().stream().map(purchaseStorage -> {
            PurchaseStorageVO vo = new PurchaseStorageVO();
            BeanUtils.copyProperties(purchaseStorage, vo);

            // 设置状态描述
            vo.setStorageStatusDesc(getStorageStatusDesc(purchaseStorage.getStorageStatus()));
            vo.setQcStatusDesc(getQcStatusDesc(purchaseStorage.getQcStatus()));

            // 查询并设置供应商信息
            if (purchaseStorage.getSupplierId() != null) {
                PurchaseSupplier supplier = purchaseSupplierService.getById(purchaseStorage.getSupplierId());
                if (supplier != null) {
                    vo.setSupplierName(supplier.getSupplierName());
                    vo.setSupplierCode(supplier.getSupplierCode());
                }
            }

            // 查询并设置用户信息
            if (purchaseStorage.getUId() != null) {
                TUser user = tUserService.getById(purchaseStorage.getUId());
                if (user != null) {
                    vo.setUserName(user.getRealName() != null ? user.getRealName() : user.getUsername());
                }
            }

            return vo;
        }).collect(Collectors.toList());

        voPage.setRecords(voList);

        // 添加最终返回数据的调试日志
        System.out.println("=== 最终返回的VO分页数据 ===");
        System.out.println("VO分页 - 总数:" + voPage.getTotal() +
                          ", 当前页:" + voPage.getCurrent() +
                          ", 每页大小:" + voPage.getSize() +
                          ", 总页数:" + voPage.getPages() +
                          ", 当前页数据量:" + voList.size());
        System.out.println("=== 最终返回的VO分页数据结束 ===");

        return voPage;
    }

    @Override
    public boolean addPurchaseStorage(PurchaseStorageAddDTO addDTO) {
        PurchaseStorage purchaseStorage = new PurchaseStorage();
        BeanUtils.copyProperties(addDTO, purchaseStorage);

        // 生成采购入库单号：RK + 年月日 + 随机四位数
        String storageOrderNo = generateStorageOrderNo();
        purchaseStorage.setStorageOrderNo(storageOrderNo);

        // 设置默认状态
        purchaseStorage.setStorageStatus(0); // 待入库

        // 如果入库时间为空，设置为当前时间
        if (purchaseStorage.getStorageTime() == null) {
            purchaseStorage.setStorageTime(new Date());
        }

        return this.save(purchaseStorage);
    }

    @Override
    public PurchaseStorageVO getPurchaseStorageDetail(Long id) {
        PurchaseStorage purchaseStorage = this.getById(id);
        if (purchaseStorage == null) {
            return null;
        }

        PurchaseStorageVO vo = new PurchaseStorageVO();
        BeanUtils.copyProperties(purchaseStorage, vo);

        // 设置状态描述
        vo.setStorageStatusDesc(getStorageStatusDesc(purchaseStorage.getStorageStatus()));
        vo.setQcStatusDesc(getQcStatusDesc(purchaseStorage.getQcStatus()));

        // 查询并设置供应商信息
        if (purchaseStorage.getSupplierId() != null) {
            PurchaseSupplier supplier = purchaseSupplierService.getById(purchaseStorage.getSupplierId());
            if (supplier != null) {
                vo.setSupplierName(supplier.getSupplierName());
                vo.setSupplierCode(supplier.getSupplierCode());
            }
        }

        // 查询并设置用户信息
        if (purchaseStorage.getUId() != null) {
            TUser user = tUserService.getById(purchaseStorage.getUId());
            if (user != null) {
                vo.setUserName(user.getRealName() != null ? user.getRealName() : user.getUsername());
            }
        }

        return vo;
    }

    @Override
    public boolean updatePurchaseStorage(Long id, PurchaseStorageAddDTO addDTO) {
        PurchaseStorage purchaseStorage = this.getById(id);
        if (purchaseStorage == null) {
            return false;
        }

        // 更新字段
        BeanUtils.copyProperties(addDTO, purchaseStorage, "id", "storageOrderNo");

        // 如果入库时间为空，设置为当前时间
        if (purchaseStorage.getStorageTime() == null) {
            purchaseStorage.setStorageTime(new Date());
        }

        return this.updateById(purchaseStorage);
    }

    /**
     * 生成采购入库单号
     * @return 采购入库单号
     */
    private String generateStorageOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());

        // 生成4位随机数
        Random random = new Random();
        int randomNum = random.nextInt(9000) + 1000; // 1000-9999

        return "RK" + dateStr + randomNum;
    }

    /**
     * 获取入库状态描述
     * @param status 状态码
     * @return 状态描述
     */
    private String getStorageStatusDesc(Integer status) {
        if (status == null) return "";
        switch (status) {
            case 0: return "待入库";
            case 1: return "部分入库";
            case 2: return "全部入库";
            default: return "未知状态";
        }
    }

    /**
     * 获取质检状态描述
     * @param status 状态码
     * @return 状态描述
     */
    private String getQcStatusDesc(Integer status) {
        if (status == null) return "";
        switch (status) {
            case 0: return "待质检";
            case 1: return "已质检";
            case 2: return "免检";
            default: return "未知状态";
        }
    }
}




